# -*- coding:utf-8 -*-

from fastapi import APIRouter, Depends, Request, Security, BackgroundTasks

from utils.response import ResponsePage, ResponseModel, Page
from utils.dependence import get_page_filter, PageFilter

from core.exceptions import ServiceException

from services.user import UserService, check_login_user
from schemas.user import User, UserCreate, UserUpdate, UserPasswordIn, UserRoleIn, UserRole


router = APIRouter(prefix="/user")

@router.get("", response_model=ResponsePage[User], summary="用户列表查询", dependencies=[Security(check_login_user, scopes=["admin:user:access"])])
async def pages(page_no: int=1, page_size: int=10, page_filter: PageFilter = Depends(get_page_filter), service: UserService = Depends(UserService)):
    page = await service.pages(page_no, page_size, page_filter)
    return ResponsePage.successed(data=Page[User].from_orm(page))

@router.get("/info/{id}", response_model=ResponseModel[User], summary="用户信息查询", dependencies=[Security(check_login_user, scopes=["admin:user:access"])])
async def info_by_id(id: int, service: UserService = Depends(UserService)):
    data_db = await service.get_by_id(id)
    if not data_db:
        raise ServiceException(404, message="用户不存在")
    return ResponseModel.successed(data=User.from_orm(data_db))

@router.get("/info", response_model=ResponseModel[User], summary="当前用户信息查询", dependencies=[Security(check_login_user, scopes=["admin:user:access"])])
async def info_me(request: Request, service: UserService = Depends(UserService)):
    if not hasattr(request.state, "user"):
        raise ServiceException(code=401, message="用户未登录")
    id = request.state.user.id
    data_db = await service.get_by_id(id)
    return ResponseModel.successed(data=User.from_orm(data_db))


@router.put("/info/avatar/{avatar}", response_model=ResponseModel[User], summary="用户头像修改", dependencies=[Security(check_login_user, scopes=["admin:user:update"])])
async def update_avatar_by_id(request: Request, avatar: int, service: UserService = Depends(UserService)):
    id = request.state.user.id
    data_db = await service.update_avatar(request, id, avatar)
    return ResponseModel.successed(data=User.from_orm(data_db))


@router.post("/", response_model=ResponseModel[User], summary="用户信息新增", dependencies=[Security(check_login_user, scopes=["admin:user:create"])])
async def do_create_user(request: Request, data: UserCreate, service: UserService = Depends(UserService)):
    data_db = await service.create(request, data)
    return ResponseModel.successed(message="用户信息新增成功", data=User.from_orm(data_db))


@router.post("/users", response_model=ResponseModel[list[User]], summary="用户信息新增", dependencies=[Security(check_login_user, scopes=["admin:user:create"])])
async def do_create_users(request: Request, datas: list[UserCreate], service: UserService = Depends(UserService)):
    datas_db = []
    for data in datas:
        data_db = await service.create(request, data)
        datas_db.append(User.from_orm(data_db))
    return ResponseModel.successed(message="用户信息新增成功", data=datas_db)


@router.post("/register", response_model=ResponseModel[User], summary="用户注册")
async def do_register(request: Request, data: UserCreate, tasks: BackgroundTasks, service: UserService = Depends(UserService)):
    data_db = await service.create(request, data)
    link = await generate_link(data_db.email)
    tasks.add_task(send_message, Email(subject="激活账号", addresses=[data_db.email], content=link))
    return ResponseModel.successed(message="注册成功", data=User.from_orm(data_db))

@router.get("/activity/{token}", response_model=ResponseModel[User], summary="用户激活")
async def do_activity(request: Request, token: str, service: UserService = Depends(UserService)):
    data = await verify_link(token)
    data_db = await service.first(User.from_orm({'email': data.get('email', None)}))
    if data_db is None:
        raise ServiceException(code=404, message="用户不存在")
    await service.update(request, data_db.id, User.from_orm({'status': 1}))
    return ResponseModel.successed(message="激活成功", data=User.from_orm(data_db))


@router.delete("/{id}", response_model=ResponseModel[User], summary="用户信息删除", dependencies=[Security(check_login_user, scopes=["admin:user:delete"])])
async def do_delete_user(request: Request, id: int, service: UserService = Depends(UserService)):
    data_db = await service.delete(request, id)
    return ResponseModel.successed(message="用户信息删除成功", data=User.from_orm(data_db))


@router.put("/{id}", response_model=ResponseModel[User], summary="用户信息更新", dependencies=[Security(check_login_user, scopes=["admin:user:update"])])
async def do_update_user(request: Request, id: int, data: UserUpdate, service: UserService = Depends(UserService)):
    data_db = await service.update(request, id, data)
    return ResponseModel.successed(message="用户信息更新成功", data=User.from_orm(data_db))

@router.put("/password/{id}", response_model=ResponseModel[User], summary="用户密码更新", dependencies=[Security(check_login_user, scopes=["admin:user:update"])])
async def do_update_user(request: Request, id: int, data: UserPasswordIn, service: UserService = Depends(UserService)):
    data_db = await service.update_password(request, id, data)
    return ResponseModel.successed(message="用户密码更新成功", data=User.from_orm(data_db))


@router.get("/roles", response_model=ResponseModel[UserRole], summary="用户角色信息查询", dependencies=[Security(check_login_user, scopes=["admin:user:role:access"])])
async def roles_me_by_id(request: Request, service: UserService = Depends(UserService)):
    if not hasattr(request.state, "user"):
        raise ServiceException(code=401, message="用户未登录")
    data_db = await service.get_by_id(request.state.user.id)
    roles = await service.get_role_permisions_by_user_id(data_db.id)
    print(roles[0].permisions)
    data_db.roles = roles
    return ResponseModel.successed(data=UserRole.from_orm(data_db))

@router.get("/{id}/roles", response_model=ResponseModel[UserRole], summary="用户角色信息查询", dependencies=[Security(check_login_user, scopes=["admin:user:role:access"])])
async def roles_by_id(id: int, service: UserService = Depends(UserService)):
    data_db = await service.get_by_id(id)
    roles = await service.get_role_permisions_by_user_id(data_db.id)
    data_db.roles = roles
    return ResponseModel.successed(data=UserRole.from_orm(data_db))

@router.put("/{id}/roles", response_model=ResponseModel[UserRole], summary="用户角色信息修改", dependencies=[Security(check_login_user, scopes=["admin:user:role:update"])])
async def update_roles_by_id(request: Request, id: int, userRole: UserRoleIn, service: UserService = Depends(UserService)):
    data_db = await service.update_role_by_user_id(request, id, userRole.roles)
    return ResponseModel.successed(data=UserRole.from_orm(data_db))

@router.put("/{id}/avatar/{avatar}", response_model=ResponseModel[User], summary="用户头像修改", dependencies=[Security(check_login_user, scopes=["admin:user:update"])])
async def update_avatar_by_id(request: Request, id: int, avatar: int, service: UserService = Depends(UserService)):
    data_db = await service.update_avatar(request, id, avatar)
    return ResponseModel.successed(data=User.from_orm(data_db))
